# -*- coding: utf8 -*-
import logging
import re
import common

site_index = 'uta_net'
site_keyword = 'uta-net'
site_url = 'http://www.uta-net.com/'
test_url = 'http://www.uta-net.com/user/phplib/view_0.php?ID=17248'

def get_lyric(url):
    prefix = 'http://www.uta-net.com/user/phplib/swf/showkasi.php?ID='
    suffix = '&WIDTH=422&HEIGHT=608'
    pattern = 'ID=([0-9]+)'

    bool = re.compile(pattern).search(url)

    if bool:
        id = bool.group(1)
        full_url = prefix + id

        # get data
        data = common.get_url_content(full_url)

        # strip the useless part
        start_str = '<\0\0'
        end_str = '\0'
        pos = data.find(start_str)
        start = pos + len(start_str)
        end = data.find(end_str, start)
        lyric = data[start:end]

        lyric = unicode(lyric, 'utf8')
        lyric = lyric.strip()

        # test for half to full
        lyric = common.half2full(lyric)


        song_info = _get_song_info(url)
        lyric = song_info + lyric

        return lyric

    return None

def _get_song_info(url):
    bytes = common.get_url_content(url)

    encoding = 'sjis'
    html = bytes.decode(encoding, 'ignore')

    pattern = u'<h2>([^<]+)</h2>'
    title = common.get_first_group_by_pattern(html, pattern)
    pattern = u'歌手：<h3>([^<]+)</h3>'
    artist = common.get_first_group_by_pattern(html, pattern)
    pattern = u'作詞：<h4>([^<]+)</h4>'
    lyric = common.get_first_group_by_pattern(html, pattern)
    pattern = u'作曲：<h4>([^<]+)</h4>'
    music = common.get_first_group_by_pattern(html, pattern)

    lines = []
    lines.append(u'%s' % (title))
    lines.append(u'')
    lines.append(u'歌手：%s' % (artist))
    lines.append(u'作詞：%s' % (lyric))
    lines.append(u'作曲：%s' % (music))

    lines.append('\n\n')

    string = '\n'.join(lines)

    return string

if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG)
    url = test_url
    print url
    lyric = get_lyric(url)
    print repr(lyric) 
